import $ from 'jquery'
import jsPlumb from 'jsPlumb'
import {randstr} from "../util";
import {FlowTree,FlowNode} from "../cls/Node";

let labelHollow = (isSource,label) => {
    let connectorPaintStyle = {
        lineWidth:4,
        strokeStyle:"#61B7CF",
        fillStyle:'transparent',
        radius:3
    }
    let connectorHoverStyle = {
        lineWidth:4,
        strokeStyle:"#216477",
        outlineWidth:2,
        outlineColor:"white"
    }
    let paintStyle = {
        strokeStyle:"#1e8151",
        fillStyle:"#1e8151",
        radius: 3,
        lineWidth: 2
    }
    return {
        DragOptions: { cursor: 'pointer', zIndex: 2000 },
        endpoint: ["Dot", { radius: 2 }],
        ConnectorStyle:connectorPaintStyle,
        ConnectorHoverStyle:connectorHoverStyle,
        EndpointHoverStyles:{
            fillStyle: "#216477",
            strokeStyle: "#216477"
        },
        PaintStyle:paintStyle,
        isSource:isSource,
        connector:["Flowchart",{ curviness:50 }],
        isTarget:!isSource,
        maxConnections:-1,
        connectorOverlays: ((label == undefined || label == '')?[["Arrow", { width: 10, length: 10, location: 1 }]]:[
            ["Arrow", { width: 10, length: 10, location: 1 }],
            [ "Label", { label:label,cssClass:"csslabel"} ]
        ])
    }
}

let hollowCircle = labelHollow(false)
let hollowCircle0 = labelHollow(true,"no")
let hollowCircle1 = labelHollow(true,"yes")
let hollowCircle00 = labelHollow(true,"error")
let hollowCircle11 = labelHollow(true,"success")
let hollowCircle2 =  labelHollow(true)
export let procedureShadow = {
    start:$('<div class = "procedure-node radius" data-node = "start">开始<i class = "fa fa-arrows-alt alt" contenteditable="false"></i></div>'),
    assign:$('<div class = "procedure-node" data-node = "assign">赋值<i class = "fa fa-arrows-alt alt" contenteditable="false"></i></div>'),
    data:$('<div class = "procedure-node parallelogram" data-node = "data">数据<i class = "fa fa-arrows-alt alt" contenteditable="false"></i></div>'),
    judge:$('<div class = "procedure-node diamond" data-node="judge"><div class = "rediamond">判断</div><i class = "fa fa-arrows-alt alt" contenteditable="false"></i></div>'),
    end:$('<div class = "procedure-node radius" data-node="end">结束<i class = "fa fa-arrows-alt alt" contenteditable="false"></i></div>'),
    request:$('<div class = "procedure-node circle" data-node="request">网络请求<i class = "fa fa-arrows-alt alt" contenteditable="false"></i></div>'),
    subprocess:$('<div class = "procedure-node subprocess" data-node="subprocess">子流程<i class = "fa fa-arrows-alt alt" contenteditable="false"></i></div>')
}

export function addEndPoint(id, name) {
    let ret = []
    switch(name) {
        case 'start':
            let point = jsPlumb.addEndpoint(id, {anchors:"BottomCenter"},hollowCircle2)
            ret.push(point)
            break
        case 'assign':
            let p1 = jsPlumb.addEndpoint(id, {anchors:"TopCenter"},hollowCircle)
            let p2 = jsPlumb.addEndpoint(id, {anchors:"BottomCenter"},hollowCircle2)
            ret.push(p1),ret.push(p2)
            break
        case 'data':
            let p0 = jsPlumb.addEndpoint(id, {anchors:"TopCenter"},hollowCircle)
            let p11 = jsPlumb.addEndpoint(id, {anchors:"BottomCenter"},hollowCircle2)
            ret.push(p0),ret.push(p11)
            break
        case 'judge':
            let p111 = jsPlumb.addEndpoint(id, {anchors:"TopCenter"},hollowCircle)
            let p222 = jsPlumb.addEndpoint(id, {anchors:"RightMiddle"},hollowCircle0)
            let p333 = jsPlumb.addEndpoint(id, {anchors:"LeftMiddle"},hollowCircle1)
            let p444 = jsPlumb.addEndpoint(id, {anchors:"BottomCenter"},hollowCircle2)
            ret.push(p111),ret.push(p222),ret.push(p333),ret.push(p444)
            break
        case 'end':
            let p1111 = jsPlumb.addEndpoint(id, {anchors:"TopCenter"},hollowCircle)
            ret.push(p1111)
            break
        case 'request':
            let p11111 = jsPlumb.addEndpoint(id, {anchors:"TopCenter"},hollowCircle)
            let p22222 = jsPlumb.addEndpoint(id, {anchors:"RightMiddle"},hollowCircle00)//error
            let p33333 = jsPlumb.addEndpoint(id, {anchors:"LeftMiddle"},hollowCircle11)//success
            let p44444 = jsPlumb.addEndpoint(id, {anchors:"BottomCenter"},hollowCircle2)//
            ret.push(p11111),ret.push(p22222),ret.push(p33333),ret.push(p44444)
            break
        case 'subprocess':
            let p111111 = jsPlumb.addEndpoint(id, {anchors:"TopCenter"},hollowCircle)
            let p222222 = jsPlumb.addEndpoint(id, {anchors:"BottomCenter"},hollowCircle2)
            ret.push(p111111),ret.push(p222222)
            break
    }
    return ret
}

export function init_procedure_view(project){
    $(".procedure-node").draggable({
        helper:'clone',
        scope:'procedure',
        handle:'.alt',
        stop:()=>{
            jsPlumb.repaintEverything()
        }
    })
    $("#procedurebox").droppable({
        scope:"procedure",
        drop:function(event, ui) {
            project.scene = 'procedure'
            if(project.procedure_file ===  null) {
                alert("未选择流程文件")
                return
            }
            let name = $(ui.draggable[0]).attr("data-node")
            let id = randstr()
            let node = $(ui.helper).clone()
            node.attr("id",id)
            node.attr("contenteditable","true")
            $(this).append(node)
            addEndPoint(id, name)
            $("#" + id).draggable({containment:"parent",handle:".alt",stop:()=>{jsPlumb.repaintEverything()}})
            node.on("click",function(e){
                project.cur_procedure = id
            })

        }
    })
}
export function save_procedure(project) {
    let tree = new FlowTree()
    $.each(jsPlumb.getAllConnections(), function (idx, connection) {
        let targetId = connection.targetId
        let sourceId = connection.sourceId
        let $source = $("#" + sourceId)
        let $target = $("#" + targetId)
        let node = tree.get(sourceId)
        if(!node) {//没有当前节点
            let content = $source.text()
            let type = $source.attr("data-node")
            let left = $source.position().left
            let top = $source.position().top
            node = new FlowNode(sourceId, type, content)
            node.setPosition(left, top)
            tree.addNode(node)
        }
        let targetNode = tree.get(targetId)
        if(!targetNode) {
            let content = $target.text()
            let type = $target.attr("data-node")
            let left = $target.position().left
            let top = $target.position().top
            targetNode = new FlowNode(targetId,type,content)
            targetNode.setPosition(left,top)
            tree.addNode(targetNode)
        }
        if(node.type === "request") {
            let url = $source.attr("url")
            let method = $source.attr("method")
            let params = $source.attr("params")
            node.setAttr("url",url)
            node.setAttr("method",method)
            node.setAttr("params",params)
        }
        let agg = ""
        if(node.type === "judge") {
            let endpoint = connection.endpoints[0]
            if(endpoint.anchor.type === "RightMiddle"){
                agg = "no"
            }else if(endpoint.anchor.type == "LeftMiddle") {
                agg = "yes"
            }
        }else if(node.type === "request") {
            let endpoint = connection.endpoints[0]
            if(endpoint.anchor.type === "RightMiddle"){
                agg = "error"
            }else if(endpoint.anchor.type == "LeftMiddle") {
                agg = "success"
            }
        }
        if(!node.hasSpan(targetId, agg)){
            node.addSpan(targetId, agg)
        }
    })
    project.procedure_file.write(JSON.stringify(tree))
}

export function update_procedure(panel, project) {
    //移除所有面板上的连接和节点
    let childs = $("#" + panel).children(".procedure-node")
    for(let i = 0;i < childs.length;i++) {

        jsPlumb.remove($(childs[i]).attr("id"))
    }
    project.procedure_file.mkView($("#" + panel), addEndPoint,(el)=>{
        el.draggable({containment:"parent",handle:".alt",stop:()=>{jsPlumb.repaintEverything()}})
        el.on("click",function(e){
            project.cur_procedure = id
        })
    })
}